﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Common;
using System.IO;
using CRL.DBAccess;
using CRL;
using Microsoft.Data.Sqlite;

namespace CRL.Sqlite
{
    public class SqliteHelper : DBHelper
    {
        /// <summary>
        /// 根据参数类型实例化
        /// </summary>
        /// <param name="_connectionString">内容</param>
		public SqliteHelper(DBAccessBuild dBAccessBuild)
            : base(dBAccessBuild)
        { }

        public override DBType CurrentDBType
        {
            get
            {
                return DBType.SQLITE;
            }
        }

        protected override DbDataAdapter CreateDa(string cmdText, IDbConnection conn)
        {
            return new SqliteDataAdapter(cmdText, (SqliteConnection)conn);
        }
        protected override IDbConnection CreateConn()
        {
            return new SqliteConnection(ConnectionString);
        }

        /// <summary>
        /// 根据表插入记录,dataTable需按查询生成结构
        /// </summary>
        /// <param name="dataTable"></param>
        /// <param name="tableName"></param>
        /// <param name="keepIdentity"></param>
        public override void InsertFromDataTable(DataTable dataTable, string tableName, bool keepIdentity = false)
        {
            var conn = (currentConn ?? CreateConn()) as SqliteConnection;
            using (var tran = _trans ?? conn.BeginTransaction())
            {
                try
                {
                    using (SqliteCommand command = new SqliteCommand("Insert into data( id, name ) values( @id, @name )", conn))
                    {
                        foreach (DataRow drData in dataTable.Rows)
                        {
                            command.Parameters.Add(new SqliteParameter("@id", drData["id"]));
                            command.Parameters.Add(new SqliteParameter("@name", drData["name"]));
                            command.ExecuteNonQuery();
                            command.Parameters.Clear();
                        }
                    }
                    tran.Commit();
                }
                catch
                {
                    tran.Rollback();
                    throw;
                }
            }
        }
    }

}
